import 'package:aitao_flutter/common_ui/circle_avatar.dart';
import 'package:aitao_flutter/model/home_item_model.dart';
import 'package:aitao_flutter/request/api.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/style/text_style.dart';
import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../refresh/custom_refresh_footer.dart';
import '../../refresh/custom_refresh_header.dart';
import '../../request/requestManager.dart';
import '../../routes/routes.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  List<HomeItemModel> itemList = [];
  int typeIndex = 0;
  int page = 1;
  int totalPage = 1;
  TextEditingController controller = TextEditingController();
  final RefreshController refreshController =
      RefreshController(initialRefresh: false);
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: Column(
        children: [
          Container(
            padding: EdgeInsetsStyle.customMargin(14, 0, 24, 0),
            // width: 200,
            child: Row(children: [
              GestureDetector(
                child: const Icon(
                  Icons.arrow_back_ios_new_sharp,
                ),
                onTap: () {
                  Get.back();
                },
              ),
              Box.hBox20,
              Expanded(
                  child: Container(
                      padding: const EdgeInsets.fromLTRB(25, 0, 25, 0),
                      decoration: BoxDecoration(
                          color: ColorStyle.f3f3f3Color,
                          borderRadius: RadiusStyle.radiusAll(16)),
                      child: TextField(
                        controller: controller,
                        textInputAction: TextInputAction.done,
                        // onChanged: (txt) {
                        //   controller.text = txt;
                        // },
                        onSubmitted: (txt) {
                          page = 1;
                          searchClick();
                        },
                        decoration: const InputDecoration(
                            hintText: '搜索ID或者昵称',
                            border: InputBorder.none,
                            hintStyle: TextStyle(
                                fontSize: 14, color: ColorStyle.color777777)),
                      )))
            ]),
          ),
          Expanded(
              child: SmartRefresher(
            controller: refreshController,
            enablePullDown: true,
            enablePullUp: page < totalPage,
            onRefresh: onRefresh,
            onLoading: onLoading,
            header: CustomClassicHeader(),
            footer: const CustomClassicFooter(),
            child: CustomScrollView(
              slivers: [
                SliverList.builder(
                  itemBuilder: (context, index) {
                    return _listItem(index);
                  },
                  itemCount: itemList.length,
                )
              ],
            ),
          ))
        ],
      ),
    ));
  }

  Widget _listItem(int index) {
    HomeItemModel m = itemList[index];
    return GestureDetector(
      child: Container(
        color: ColorStyle.whiteColor,
        padding: const EdgeInsets.all(10),
        child: Row(children: [
          CircleAvatarWidget(
            url: m.avatar ?? '',
            gender: m.gender ?? 1,
            imgHeight: 48,
            imgWidth: 48,
          ),
          Box.hBox10,
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                m.nickname ?? '',
                style: Styles.normalText_15,
              ),
              Row(
                children: [
                  Text(
                    m.city ?? '',
                    style: Styles.greyText_13,
                  ),
                  Box.hBox3,
                  Text(
                    '|',
                    style: Styles.greyText_13,
                  ),
                  Box.hBox3,
                  Text(
                    '${m.age ?? 18}岁',
                    style: Styles.blueText_13,
                  )
                ],
              ),
            ],
          ),
          const Spacer(),
          Text(
            m.dateline ?? '',
            style: Styles.greyText_13,
          )
        ]),
      ),
      onTap: () {
        Get.toNamed(Routes.personalPage,
            parameters: {'userId': m.userid.toString()});
      },
    );
  }

  void searchClick() async {
    if (controller.text == '') return;
    var result = await RequestManager()
        .post(API.homeSearch, params: {'text': controller.text, 'page': page});
    if (result != null && result['code'] == 0) {
      WJLogUtils.wjLog(result);
      itemList.clear();
      Map data = result['data'];
      // Map list = data['list'];
      page = int.parse(data['page'].toString());
      totalPage = int.parse(data['total_page'].toString());
      List tempList = data['list'];
      for (var item in tempList) {
        HomeItemModel itemModel = HomeItemModel.fromJson(item);
        itemList.add(itemModel);
      }
      setState(() {});
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.homeSearch, params: {'text': controller.text, 'page': page});
    if (result != null && result['code'] == 0) {
      Map data = result['data'];
      page = int.parse(result['data']['page'].toString());
      totalPage = result['data']['total_page'];
      List tempList = data['list'];
      for (var item in tempList) {
        HomeItemModel itemModel = HomeItemModel.fromJson(item);
        itemList.add(itemModel);
      }
      setState(() {});
    }
  }

  void onRefresh() {
    page = 1;
    totalPage = 1;
    searchClick();
    refreshController.refreshCompleted();
  }

  void onLoading() async {
    page += 1;
    loadMoreList();
    refreshController.loadComplete();
  }
}
